<template>
  <!--原授权信息  -->
  <!--注册信息  -->
  <div>
    <FormPanel ref="FormPanel" :list="initForm" :cols="3" :formType="formType" :labelWidth="180" :isSubmitBtn="false" @formChange="formChangeHandle" class="mtop" />
    <FilterTable
      height="auto"
      ref="tableInfo"
      :columns="columns"
      :isSelectColumn="false"
      selectionType="single"
      :isMemoryPagination="true"
      :onSyncTableData="syncFun"
      :datakey="'records'"
      :isToperInfo="false"
      :onColumnsChange="columns => (this.columns = columns)"
      columnsRef="notification_maintain_info_02">

      <template slot="controls">
<!--        <el-button v-show=" formType == 'add' || formType == 'edit'" size="small" type="primary" icon="el-icon-plus" @click="addFun()">新增</el-button>-->
      </template>
    </FilterTable>
  </div>
</template>
<div id="allmap" style="width:0px;height:0px;"></div>
<script>
import { dictionary } from '@/utils/dictMixin';
import * as utils from '@/utils';
import * as types from '@/api/cms-api/origin/originInfo/types';
import {doubleCheck} from '@/utils/validate.js';
import config from '@/assets/js/config';
import * as bqutils from '@/utils/utils'; //工具类

import vm from './bridge';

import MP from '@/assets/js/map'; //地图

export default {
  mixins: [dictionary],
  model: {
    prop: 'pdata',
    event: 'click'
  },
  props: {
    pdata: {
      type: Object,
      default: () => ({})
    },
    formType: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      initForm: this.initFormFun(),
      columns: this.createColumns(),
      isSelectColumn: true,
      map: undefined,
      saveData: {
        editType: '',
        xxList: []
      }
    };
  },
  mounted() {
    //注册经销商类型变化时触发的事件
    //在审核时，给此页面的类型为只读，但是基本信息（infoBase可以编辑，会显示会触发事件，事件会触发禁用取消，覆盖整个表单的类型（表单类型为show，但是依旧可以输入，（部分）））
    if (this.formType != 'show') {
      vm.$on('changeDealerType', this.changeDealerType);
    }
  },
  methods: {
    //初始化数据（由外部调用）
    init() {
      this.initForm.forEach(x => {
        //为空不赋值
        if (this.pdata[x.fieldName]) {
          //如果是‘电池联合服务中心’则需要特殊处理一下，否则会出现类型不一致导致回显出现问题
          if (x.fieldName === 'batteryServiceStation') {
            x.initialValue = Number(this.pdata[x.fieldName]);
          } else {
            x.initialValue = this.pdata[x.fieldName];
          }
        }
      });
      this.$refs.tableInfo.EXECUTE_INSERT(this.pdata.insertEquityList);
    },
    //表单验证通过后
    formChangeHandle(val) {
      this.pdata = Object.assign(this.pdata, val);
      //传递数据到父组件里
      this.$emit('click', this.pdata);
    },
    //开放的保存方法
    async saveDialog() {
      let flag = true;
      let err = this.$refs.FormPanel.SUBMIT_FORM();
      await this.$refs.FormPanel.$refs.form.validate().then(res => {
        console.log("res1:", res);
      }).catch(err => {
        console.log("err1:", err);
        flag = false;
      });
      console.log("flag:", flag);
      return flag;
      // this.$notify.warning({title: '提示信息',message:'只能选择一条记录'});
    },
    //经销商类型变更时
    changeDealerType(value) {
      //根据类型处理验证
      if (types.DEALER_INFO_DEALER_TYPE_4S === value) {
        //4S
        vm.changeForm(this.initForm, '4S', false);
        vm.clearValidate(this.$refs.FormPanel);
      } else if (types.DEALER_INFO_DEALER_TYPE_SINGLE_AFTER_SALE === value) {
        //单一售后
        vm.changeForm(this.initForm, 'SH', false);
        vm.clearValidate(this.$refs.FormPanel);
      } else if (types.DEALER_INFO_DEALER_TYPE_SINGLE_SALE === value) {
        //单一销售
        vm.changeForm(this.initForm, 'XS', false);
        vm.clearValidate(this.$refs.FormPanel);
      } else if (types.DEALER_INFO_DEALER_TYPE_DIRECT_SHOP === value) {
        //SPACE
        vm.changeForm(this.initForm, 'SPACE', false);
        vm.clearValidate(this.$refs.FormPanel);
      } else if (types.DEALER_INFO_DEALER_TYPE_NO_DIRECT_SHOP === value) {
        //RACE
        vm.changeForm(this.initForm, 'RACE', false);
        vm.clearValidate(this.$refs.FormPanel);
      } else if (types.DEALER_INFO_DEALER_TYPE_BIG_CUSTOMER === value) {
        //大客户
        vm.changeForm(this.initForm, 'DKH', false);
        vm.clearValidate(this.$refs.FormPanel);
      }

    },
    //销售获取经纬度
    saleAdress() {
      let self = this;
      //获取地址
      let salesAddress = this.initForm.find(x => x.fieldName === 'salesAddress').initialValue;
      if (salesAddress) {
        var city = '';
        if (salesAddress.indexOf('北京') >= 0) {
          city = '北京市';
        } else if (salesAddress.indexOf('上海') >= 0) {
          city = '上海市';
        } else if (salesAddress.indexOf('天津') >= 0) {
          city = '天津市';
        } else if (salesAddress.indexOf('重庆') >= 0) {
          city = '重庆市';
        } else if (salesAddress.indexOf('内蒙古') >= 0) {
          city = '内蒙古自治区';
        } else if (salesAddress.indexOf('宁夏') >= 0) {
          city = '宁夏回族自治区';
        } else if (salesAddress.indexOf('新疆') >= 0) {
          city = '新疆维吾尔自治区';
        } else if (salesAddress.indexOf('西藏') >= 0) {
          city = '西藏自治区';
        } else if (salesAddress.indexOf('广西') >= 0) {
          city = '广西壮族自治区';
        } else if (salesAddress.indexOf('香港') >= 0) {
          city = '香港';
        } else if (salesAddress.indexOf('澳门') >= 0) {
          city = '澳门';
        } else if (salesAddress.indexOf('省') >= 0) {
          city = salesAddress.substring(0, salesAddress.indexOf('省') + 1);
        } else {
          this.$notify.warning({ title: '提示信息', message: '请输入正确的销售运营地址!' });
          return;
        }

        MP().then(BMap => {
          var map = new BMap.Map('allmap');
          // 创建地址解析器实例
          var myGeo = new BMap.Geocoder();
          // 获取地址经纬度
          myGeo.getPoint(
            salesAddress,
            function(point, e) {
              if (e) {
                self.initForm.find(x => x.fieldName === 'salesLongitude').initialValue = point.lng;
                self.initForm.find(x => x.fieldName === 'salesLatitude').initialValue = point.lat;
              } else {
                self.$notify.warning({ title: '提示信息', message: '请输入正确的销售运营地址!' });
              }
            },
            city
          );
        });
      } else {
        this.$notify.warning({ title: '提示信息', message: '请输入销售运营地址!' });
      }
    },
    //售后获取经纬度
    buyAdress() {
      let self = this;
      //获取地址
      let serviceAddress = this.initForm.find(x => x.fieldName === 'serviceAddress').initialValue;
      if (serviceAddress) {
        var city = '';
        if (serviceAddress.indexOf('北京') >= 0) {
          city = '北京市';
        } else if (serviceAddress.indexOf('上海') >= 0) {
          city = '上海市';
        } else if (serviceAddress.indexOf('天津') >= 0) {
          city = '天津市';
        } else if (serviceAddress.indexOf('重庆') >= 0) {
          city = '重庆市';
        } else if (serviceAddress.indexOf('内蒙古') >= 0) {
          city = '内蒙古自治区';
        } else if (serviceAddress.indexOf('宁夏') >= 0) {
          city = '宁夏回族自治区';
        } else if (serviceAddress.indexOf('新疆') >= 0) {
          city = '新疆维吾尔自治区';
        } else if (serviceAddress.indexOf('西藏') >= 0) {
          city = '西藏自治区';
        } else if (serviceAddress.indexOf('广西') >= 0) {
          city = '广西壮族自治区';
        } else if (serviceAddress.indexOf('香港') >= 0) {
          city = '香港';
        } else if (serviceAddress.indexOf('澳门') >= 0) {
          city = '澳门';
        } else if (serviceAddress.indexOf('省') >= 0) {
          city = serviceAddress.substring(0, serviceAddress.indexOf('省') + 1);
        } else {
          this.$notify.warning({ title: '提示信息', message: '请输入正确的售后运营地址!' });
          return;
        }

        MP().then(BMap => {
          var map = new BMap.Map('allmap');
          // 创建地址解析器实例
          var myGeo = new BMap.Geocoder();
          // 获取地址经纬度
          myGeo.getPoint(
            serviceAddress,
            function(point, e) {
              if (e) {
                self.initForm.find(x => x.fieldName === 'serviceLongitude').initialValue = point.lng;
                self.initForm.find(x => x.fieldName === 'servicesLatitude').initialValue = point.lat;
              } else {
                self.$notify.warning({ title: '提示信息', message: '请输入正确的售后运营地址!' });
              }
            },
            city
          );
        });
      } else {
        this.$notify.warning({ title: '提示信息', message: '请输入售后运营地址!' });
      }
    },
    //搜索数据
    initFormFun() {
      let bt = { required: true, message: '必填', trigger: ['change', 'blur'] };
      let btl = [bt];
      let jy = { disabled: true };
      let yc = { hidden: true };
      return [
        {
          type: 'INPUT',
          label: '法人',
          fieldName: 'representative',
          initialValue: '',
          maxlength: 30,
        },
        {
          type: 'INPUT',
          label: '法人联系方式',
          fieldName: 'representativeTel',
          initialValue: '',
          maxlength: 30,
        },
        {
          type: 'INPUT',
          label: '法人邮箱',
          fieldName: 'representativeEmail',
          initialValue: '',
          maxlength: 30,
        },
        {
          type: 'INPUT',
          label: '注册资金（万元）',
          fieldName : 'registeredCapital',
          placeholder: '请输入',
          initialValue: '',
          maxlength: 8,
          rules: [
            { validator: doubleCheck, trigger: 'blur'}
          ]
        },
        {
          type: 'INPUT',
          label: '统一社会信用代码',
          fieldName : 'unifiedSocialCreditCode',
          placeholder: '请输入',
          initialValue: '',
          maxlength: 30,
        },
        {
          type: 'DATE',
          format: 'yyyy-MM-dd',
          dateType: 'exactdate',
          label: '成立时间',
          fieldName : 'establishmentDate',
          placeholder: '请输入',
          initialValue: '',
        },
        {
          type: 'INPUT',
          label: '注册地址',
          fieldName : 'registerAddress',
          placeholder: '请输入',
          selfCols: 2,
          initialValue: '',
          disabled:true,
          maxlength: 255,
        },
        {
          type: 'UPLOAD_FILE',
          label: '附件下载',
          fieldName: 'caseUrl',
          initialValue: [],
          disabled: true,
          selfCols: 3 ,
          upload: {
            actionUrl: `${config.uploadUrl}/api/file/oss/upload`, // 上传的地址
            limit: 10,
            fileTypes: ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'rar', 'zip', 'txt', 'ppt', 'pptx', 'doc', 'docx', 'xls', 'xlsx'],
            max: 1024 * 200
          }
        }
      ];

    },
    createColumns(){
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          editable: false,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 50,
        //   fixed: 'left',
        //   editable: false,
        // },
        {
          title: '股权结构名称',
          dataIndex: 'shareholderName',
          filterType: 'input',
          editRequired: false,
          sorter: true,
          editable: false,
          maxlength: 30,
        },
        {
          title: '股权结构占比',
          dataIndex: 'equityRatio',
          filterType: 'input',
          editRequired: false,
          sorter: true,
          editable: false,
          maxlength: 3,
        },
        {
          title: '股权结构金额',
          dataIndex: 'inputAmount',
          filterType: 'input',
          editRequired: false,
          sorter: true,
          editable: false,
          maxlength: 15,
          // render: props=>{
          //   return <span>props.row.inputAmount.toFixed(2)</span>
          // }
        },
      ];
    },
    syncFun(details){
      this.saveData.xxList = details
    },
    addFun(){
      if(this.saveData.xxList.length == 10){
        this.$notify.warning({title: '提示信息',message:'股权结构数量已达到上限'});
        return;
      }
      let p = {
        shareholderName: '',
        equityRatio: '',
        inputAmount: '',
      }
      this.$refs.tableInfo.EXECUTE_INSERT(p)
    },
    deleteRow(row,index) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$refs.tableInfo.EXECUTE_DELETE([row])
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
  }
};
</script>
